package cn.neusoft.controller;

import cn.neusoft.po.Employee;
import cn.neusoft.query.EmployeeQuery;
import cn.neusoft.service.IEmployeeService;
import cn.neusoft.util.TokenUtil;
import cn.neusoft.vo.LogUserVo;
import cn.neusoft.vo.ResponseObj;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hxj
 * @since 2023-12-19
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    IEmployeeService service;

    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @PostMapping
    public ResponseObj saveOrUpdate(@RequestBody Employee employee){
        //判断是否传递密码
        if (!StringUtils.hasText(employee.getPassword())){
            employee.setPassword("111111");
        }
        //对密码进行加密
        String finalPassword = passwordEncoder.encode(employee.getPassword());
        //重新设置密码为密文
        employee.setPassword(finalPassword);
        boolean b = service.saveOrUpdate(employee);
        return b?ResponseObj.SUCCESS():ResponseObj.ERROR(20001,"保存员工信息失败");
    }

    @DeleteMapping("/{id}")
    public ResponseObj delete(@PathVariable("id") Integer id){
        boolean b = service.removeById(id);
        return b?ResponseObj.SUCCESS():ResponseObj.ERROR(20002,"删除员工信息失败");
    }

    /**
    在mapper层重写了selectById的sql语句
     */
    @GetMapping("/{id}")
    public ResponseObj getById(@PathVariable("id") Integer id){
        Employee employee = service.getById(id);
        employee.setPassword(null);
        employee.setSalt(null);
        return ResponseObj.SUCCESS(employee);
    }

    @PostMapping("/page")
    public ResponseObj getByPage(@RequestBody EmployeeQuery query){
        Page<Employee> page = service.getByPage(query);
        return ResponseObj.SUCCESS(page);
    }

//    @PostMapping("/login")
//    public ResponseObj login(@RequestBody LogUserVo logUserVo){
//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.eq("username",logUserVo.getUsername());
//        Employee employee = service.getOne(queryWrapper);
//        if (employee!=null){
//            System.out.println("数据库中的密码："+employee.getPassword());
//            System.out.println("客户端提交的密码："+logUserVo.getPassword());
//            boolean matches = passwordEncoder.matches(logUserVo.getPassword(),employee.getPassword());
//            System.out.println("匹配结果："+matches);
//            return matches?ResponseObj.SUCCESS(employee):ResponseObj.ERROR(501,"密码错误");
//        }
//        return ResponseObj.ERROR(501,"用户名不存在");
//    }

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("/login")
    public ResponseObj login(@RequestBody LogUserVo logUserVo){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",logUserVo.getUsername());
        Employee employee = service.getOne(queryWrapper);
        if (employee!=null){
            System.out.println("数据库中的密码："+employee.getPassword());
            System.out.println("客户端提交的密码："+logUserVo.getPassword());
            boolean matches = passwordEncoder.matches(logUserVo.getPassword(),employee.getPassword());
            System.out.println("匹配结果："+matches);
            //用户名密码匹配无误 登录成功
            if(matches){

                //根据用户名生成token
                String token = TokenUtil.sign(employee.getUsername());
                redisTemplate.opsForValue().set(token,employee,30, TimeUnit.MINUTES);

                Map result = new HashMap<>();
                employee.setPassword(null);
                employee.setSalt(null);
                result.put("loginUser",employee);
                result.put("token",token);

                return ResponseObj.SUCCESS(result);
            }
        }
        return ResponseObj.ERROR(501,"用户名不存在");
    }

}
